﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PropertyManagment.config.jwt {
    public static class JwtBearerConfig {
        public static IServiceCollection JwtBearerService(this IServiceCollection services, JwtConfig jwtConfig) {

            Debug.WriteLine("jwt 校验 filter");

            //配置认证服务
            services.AddAuthentication(authoption => {
                authoption.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authoption.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(option => {
                option.TokenValidationParameters = new TokenValidationParameters {
                    //是否验证发行人
                    ValidateIssuer = true,
                    ValidIssuer = jwtConfig.issuer,//发行人
                     //是否验证受众人
                    ValidateAudience = true,
                    ValidAudience = jwtConfig.audience,//受众人
                    //是否验证密钥
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.signingKey)),

                    ValidateLifetime = jwtConfig.validateLifetime, //验证生命周期
                    RequireExpirationTime = true, //过期时间
                };
            });

            return services;
        }

        public static IServiceCollection RoleService(this IServiceCollection services) {
            //添加授权角色策略
            //services.AddAuthorization(options =>{
            //    options.AddPolicy("BaseRole", options => options.RequireRole("admin"));
            //});

            //services.AddAuthorization(options => {
            //    options.AddPolicy("Roles", options => options.RequireClaim("Roles", "admin"));
            //});

            //基于自定义策略授权
            //services.AddAuthorization(options => {
            //    options.AddPolicy("customizePermisson",
            //      policy => policy
            //        .Requirements
            //        .Add(new PermissionRequirement("admin")));
            //});
            ////此外，还需要在 IAuthorizationHandler 类型的范围内向 DI 系统注册新的处理程序：
            //services.AddScoped<IAuthorizationHandler, PermissionRequirementHandler>();
            //// 如前所述，要求可包含多个处理程序。如果为授权层的同一要求向 DI 系统注册多个处理程序，有一个成功就足够了。

            return services;
        }
    }
}
